package com.hoangqp.android.stardictcore;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.logging.Logger;

import android.util.Log;
public class DictFile {
	/** Logger */
	static final Logger LOG = Logger.getLogger("DictFile");
	
	/**
	 * String that get file name
	 */
	private String strFileName;
	
	/**
	 * Constructor
	 * @param fileName
	 */
	public DictFile(String fileName){
		strFileName = fileName;
	}
	
	/**
	 * Get word meaning by its offset and its meaning size.
	 * 
	 * @param offset that is get in .idx file
	 * @param size that is get in .idx file
	 * @return meaning of word data
	 */
	public String getWordData(long offset, long size){
		if(!((new java.io.File(strFileName)).exists())){
			return "File: " + strFileName + " does not exist";
		}
		String strMeaning = "not found";
		DataInputStream dt = null;
		try {
			dt = new DataInputStream(new BufferedInputStream(new FileInputStream(strFileName)));
			dt.skip(offset);
			byte[] bt = new byte[(int) size];
			dt.read(bt, 0, (int) size);
			strMeaning = new String(bt, "UTF8");
		} catch (Exception ex) {
			Log.e("Error", "Read file name '" + strFileName + "'");
		} finally {
			if(dt != null){
				try {
					dt.close();
				} catch (Exception ex){
					Log.w("Closing DataInputStream", ex);
				}
			}
		}
		return strMeaning;
	}
	
	/**
     * Add data to .dict file.
     * @param strMeaning meaning of a paticular word.
     * @return size of strMeaning.
     */
	public long addData(String strMeaning){
		DataOutputStream dt = null;
		long fileSize = -1;
		try {
			java.io.File f = new java.io.File(strFileName);
			fileSize = f.length();
			dt = new DataOutputStream(new FileOutputStream(strFileName, true));
			dt.write(strMeaning.getBytes("UTF8"));
		} catch (Exception ex){
			Log.e("Error", "Read file name '" + strFileName);
		} finally {
			if(dt != null){
				try {
					dt.close();
				} catch (Exception ex){
					Log.w("Warning", "Closing DataOutputStream");
				}
			}
		}
		return fileSize;
	}
}
